#include "./app_task.h"
#include "../cfg/ota_info.h"
#include "../conn/handler.h"
#include "../driver/cmd_uart.h"
#include "../utils/core.h"
#include "../utils/log.h"

namespace task {

AppTask appTask;

using namespace driver;
using namespace cfg;
using namespace utils;
using namespace conn;

#ifdef BUILD_BOOT
static void exec_upgrade() {

    if (otaInfo.verify() && otaInfo->is_valid()) {

        print("ota copy data");

        Error err = flash::erase(
            otaInfo->app_addr,
            otaInfo->pkg_size
        );
        if (err) {
            goto finish;
        }

        err = flash::write(
            otaInfo->app_addr,
            reinterpret_cast<const void *>(otaInfo->ota_data_addr),
            otaInfo->pkg_size
        );
        if (err) {
            goto finish;
        }

        otaInfo->reset();
        
    finish:
        if (err) {
            print("ota err:", err.err_code);
        }
    } else {
        print("no upgrade");
    }
    osDelay(500);
    core::run_process(flash::APP_ADDR);
}
#endif

void AppTask::run() {
    cmdUart.init();
    LOG_INIT();

#ifdef BUILD_APP
    print("app run version 03");
#endif

#ifdef BUILD_BOOT
    print("boot run");
    exec_upgrade();
#endif

    handler();
}

} // namespace task
